package com.levy.contronller.common;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.nutz.dao.DaoException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.levy.dto.ErrorMessage;
import com.levy.utils.exceptionBean.FailureParamException;
import com.levy.utils.exceptionBean.UniqueDaoException;

public abstract class ExceptionController {
	
	protected static final Logger log = Logger.getLogger(ExceptionController.class);
	private ErrorMessage errmsg = new ErrorMessage();
	
	/**
	 * 数据唯一性出错
	 * */
	@ExceptionHandler(UniqueDaoException.class)
	@ResponseStatus(HttpStatus.OK)
	public Map<String,ErrorMessage> uniqueDaoException(Exception e,HttpServletRequest request){
		log.error("dao unique 00000：\n" + e.getMessage());
		Map<String, ErrorMessage> result = new HashMap<String, ErrorMessage>();
		errmsg.setCode("00000");
		errmsg.setMsg("数据唯一性出错");
		result.put("error", errmsg);
		return result;
	}
	
	/**
	 * 与数据库相关操作异常
	 * */
	@ExceptionHandler(DaoException.class)
	@ResponseStatus(HttpStatus.OK)
	public Map<String,ErrorMessage> handleDaoException(Exception e,HttpServletRequest request){
		log.error("dao 00001：\n" + e.getMessage());
		Map<String, ErrorMessage> result = new HashMap<String, ErrorMessage>();
		errmsg.setCode("00001");
		errmsg.setMsg("数据库操作失败");
		result.put("error", errmsg);
		return result;
	}
	/***
	 * 数据流异常，包括lucene异常
	 * */
	@ExceptionHandler(IOException.class)
	@ResponseStatus(HttpStatus.OK)
	public Map<String,ErrorMessage> handleIOException(Exception e,HttpServletRequest request){
		log.error("IO 00002：\n" + e.getMessage());
		Map<String, ErrorMessage> result = new HashMap<String, ErrorMessage>();
		errmsg.setCode("00002");
		errmsg.setMsg("数据解析异常");
		result.put("error", errmsg);
		return result;
	}
	
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.OK)
	public Map<String,ErrorMessage> handleException(Exception e,HttpServletRequest request){
		log.error("web 00004:\n" + e.getMessage());
		Map<String, ErrorMessage> result = new HashMap<String, ErrorMessage>();
		errmsg.setCode("00004");
		errmsg.setMsg("操作失败");
		result.put("error", errmsg);
		return result;
		
	}
	@ExceptionHandler(FailureParamException.class)
	@ResponseStatus(HttpStatus.OK)
	public Map<String,ErrorMessage> paramException(FailureParamException e,HttpServletRequest request){
		log.error("JS 00003 Delivery failure parameters:\n"+ e.getMessage());
		Map<String, ErrorMessage> result = new HashMap<String, ErrorMessage>();
		errmsg.setCode("00003");
		errmsg.setMsg("参数传递错误");
		result.put("error", errmsg);
		return result;
		
	}
	
}
